<template>
  <el-card class="box-card card-main" shadow="never">
    <div slot="header">
      <el-form
        :inline="true"
        :model="serchRole"
        class="demo-form-inline"
        label-width="90px"
        label-position="right"
        size="mini"
      >
        <el-form-item label="用户名：">
          <el-input v-model="serchRole.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="用户描述：">
          <el-input v-model="serchRole.description" placeholder="请输入用户描述" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchList">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-row>
      <el-button type="primary" size="mini" @click="handleAddOrEdit()">添加角色</el-button>
    </el-row>
    <el-table :data="roleList" border stripe size="small" style="width: auto">
      <el-table-column type="selection" align="left" width="35" />
      <el-table-column prop="name" align="left" label="角色名称" />
      <el-table-column prop="description" align="left" label="角色描述" />
      <el-table-column width="150" align="left" label="创建时间">
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="200">
        <template slot-scope="scope">
          <el-button
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
            @click="handleAddOrEdit(scope.row)"
          >查看/编辑权限</el-button>
          <el-button
            v-if="scope.row.username !== 'admin'"
            type="danger"
            style="padding: 3px 4px 3px 4px;margin: 1px"
            size="mini"
            @click="deleteRow(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      :current-page="pageInfo.pageNum"
      :page-sizes="[10, 20, 30, 50]"
      :page-size="pageInfo.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="pageInfo.pageCount"
      @size-change="changePageSize"
      @current-change="changePageNum"
    />
    <!--新增、 编辑、查看权限 -->
    <el-dialog
      :title="addOrEditForm.title"
      :visible.sync="addOrEditFormVisible"
      width="500px"
      @close="closeDialog('addOrEditForm')"
    >
      <el-form
        ref="addOrEditForm"
        label-width="90px"
        :model="addOrEditForm"
        size="small"
        :rules="roleRules"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="addOrEditForm.name" auto-complete="off" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="addOrEditForm.description" auto-complete="off" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="权限配置">
          <el-tree
            ref="listTree"
            :data="allPermissions"
            :props="listTreeProps"
            node-key="id"
            :show-checkbox="true"
            :accordion="true"
            empty-text="没有权限数据"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog('addOrEditForm')">取消</el-button>
        <el-button size="small" type="primary" class="title" @click="submitForm('addOrEditForm')">保存</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { requestAllRolesByPage, requestGetchildListIDByRoleId, requestSaveByRoleId, requestDelRoleById } from '@/api/role'
import { requestAllPage } from '@/api/user'
import { successMessage } from '@/utils/message'
export default {
  name: 'Role',
  data() {
    return {
      serchRole: { name: '', description: '' },
      pageInfo: { pageNum: 1, pageSize: 10, pageCount: 0 },
      listTreeProps: {
        label: 'name',
        children: 'children'
      },
      allPermissions: [],
      roleList: [],
      addOrEditFormVisible: false, // 新增或者删除弹出框默认值
      addOrEditForm: {
        title: '',
        id: '',
        name: '',
        description: '',
        permissionIds: []
      },
      roleRules: {
        name: [
          { required: true, message: '角色名称不能为空', trigger: 'blur' },
          { pattern: /^[0-9A-Za-z]{3,10}$/, message: '角色名称由3-10位数或字字母组合', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '角色描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    serchInfo: function() {
      const pageInfo = this.pageInfo
      pageInfo.serchRole = this.serchRole
      return pageInfo
    }
  },
  mounted() {
    this.getUserPageList()
    requestAllPage().then(data => {
      this.allPermissions = data
    })
  },
  methods: {
    handleAddOrEdit(row) {
      if (row) {
        this.addOrEditFormVisible = true
        this.addOrEditForm.title = '编辑角色'
        this.addOrEditForm.id = row.id
        this.addOrEditForm.name = row.name
        this.addOrEditForm.description = row.description
        requestGetchildListIDByRoleId({ roleId: row.id }).then(data => {
          // 解决在tree未加载完成设置选择项
          data = data || []
          // console.log(data)
          this.$nextTick(() => {
            this.$refs.listTree.setCheckedKeys(data)
          })
        })
      } else {
        this.addOrEditFormVisible = true
        this.addOrEditForm.title = '新增角色'
      }
    },
    deleteRow(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        requestDelRoleById(row.id).then(data => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getUserPageList()
        })
      }).catch(() => {
        this.$message({
          type: 'success',
          message: '已取消删除'
        })
      })
    },
    resetSearch() {
      // 重置搜索条件方法
      this.serchRole = {}
    },
    searchList() {
      this.getUserPageList()
    },
    changePageSize(data) {
      // console.log('分页插件修改每页条数事件方法' + data)
      this.pageInfo.pageSize = data
      this.requestUsersInfo()
    },
    changePageNum(data) {
      // console.log('修改当前页码' + data)
      this.pageInfo.pageNum = data
      this.requestUsersInfo()
    },
    // 获取分页用户列表
    getUserPageList() {
      requestAllRolesByPage(this.serchInfo).then((result) => {
        this.roleList = result.list || {}
        this.pageInfo.pageCount = result.total
      })
    },
    submitForm(Visible) {
      this.$refs[Visible].validate((validate) => {
        if (validate && Visible === 'addOrEditForm') {
          this.addOrEditForm.permissionIds = this.$refs.listTree.getCheckedKeys().concat(this.$refs.listTree.getHalfCheckedKeys())
          requestSaveByRoleId(this.addOrEditForm).then(data => {
            this.addOrEditFormVisible = false
            this.getUserPageList()
            this.$refs[Visible].resetFields()
            successMessage('保存数据成功')
          })
        }
      })
    },
    closeDialog(Visible) {
      if (Visible === 'addOrEditForm') {
        this.addOrEditFormVisible = false
        // 重置树形组件数据
        this.$refs.listTree.setCheckedKeys([])
        this.$refs[Visible].resetFields()
      }
    }
  }
}
</script>

<style scoped>
</style>
